//
//  JFAppDelegate.m
//  TestTaskMethod
//
//  Created by ran on 13-11-13.
//  Copyright (c) 2013年 com.jingfu.ran. All rights reserved.
//

#import "JFAppDelegate.h"

@interface JFAppDelegate ()
{
    
}

@property(nonatomic,strong)NSString  *fileDir;

@end

@implementation JFAppDelegate

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    
//    [self taskComand:@"ls" arguments:[NSArray arrayWithObjects:@"-A",@"-m",@"-R", nil] dir:@"/Users/popo/Code/vim4.8_on1105/i366_V4_8_2_1029"];
    //[self startPhase];
  //  NSArray *args = @[@"/Users/popo/Code/vim4.8_on1105/i366_V4_8_2_1029", @"-name",@"*.png"];
  /// [self taskComand:@"find" arguments:args dir:@"/Users/popo/Code/vim4.8_on1105/i366_V4_8_2_1029"];
//    [self taskComand:@"find" arguments:[NSArray arrayWithObjects:@"/Users/popo/Code/vim4.8_on1105/i366_V4_8_2_1029",@"*.m", nil] dir:@"/Users/popo/Code/vim4.8_on1105/i366_V4_8_2_1029"];
    // Insert code here to initialize your application
    
    self.fileDir = [[NSUserDefaults standardUserDefaults] objectForKey:@"file"];
    if (self.fileDir) {
         [self.pathController setURL:[NSURL URLWithString:self.fileDir]];
    }
}

-(IBAction)chooseSourceDir:(id)sender
{
    NSRect  rect = {400,0,400,200};
    NSOpenPanel  *openPanel = [[NSOpenPanel alloc] initWithContentRect:rect
                                                             styleMask:NSTitledWindowMask | NSResizableWindowMask backing:NSBackingStoreBuffered defer:YES];
    
    openPanel.canChooseDirectories = YES;
    openPanel.canChooseFiles = NO;
    [openPanel setTitle:@"选择你的源文件目录"];
    [openPanel setPrompt:@"确定"];
    [openPanel runModal];
    NSString  *strFileName = [[openPanel URL] path];
    NSLog(@"path:%@",strFileName);
    self.fileDir = strFileName;
    [self.pathController setURL:[NSURL URLWithString:strFileName]];
    
    if (self.fileDir){
        [[NSUserDefaults standardUserDefaults] setObject:strFileName forKey:@"file"];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }

}

-(IBAction)startPhaseAction:(id)sender
{
    
    if (self.fileDir == nil || ![[NSFileManager defaultManager] fileExistsAtPath:self.fileDir])
    {
        NSLog(@"startPhaseAction fail because self.fileDir is %@ 请先选择工程所在目录",self.fileDir);
        return;
    }
    [self startPhase];
    
}


-(BOOL)arrayHasPrefixFileName:(NSString*)strName inArray:(NSArray*)arrayFiles
{
    NSString *strTemp = [strName stringByReplacingOccurrencesOfString:@"@2x.png" withString:@""];
    strTemp = [strTemp stringByReplacingOccurrencesOfString:@"@3x.png" withString:@""];

    for (NSString *str in arrayFiles){
        if ([str rangeOfString:strTemp].location != NSNotFound) {
            return YES;
        }
    }
    
    return NO;
}
-(void)startPhase
{
    NSArray *args = @[self.fileDir, @"-name",@"*.png"];
    
    NSMutableArray  *arraypngs = [NSMutableArray array];
    NSArray  *arraytemp = [self taskComand:@"find" arguments:args dir:self.fileDir];
    [arraypngs addObjectsFromArray:arraytemp];
    
    /*
    NSMutableArray  *arrayfiles = [NSMutableArray array];
    
    args =  @[@"/Users/popo/Code/vim4.8_on1105/i366_V4_8_2_1029", @"-name",@"*.m*"];
    [arrayfiles addObjectsFromArray:[self taskComand:@"find" arguments:args dir:@"/Users/popo/Code/vim4.8_on1105/i366_V4_8_2_1029"]];
    
    args =  @[@"/Users/popo/Code/vim4.8_on1105/i366_V4_8_2_1029", @"-name",@"*.xib"];
    [arrayfiles addObjectsFromArray:[self taskComand:@"find" arguments:args dir:@"/Users/popo/Code/vim4.8_on1105/i366_V4_8_2_1029"]];*/
    
//    NSArray  *arrComand = @[@"-rl",@"recharge_chat_right",@"/Users/popo/Code/vim4.8_on1105/i366_V4_8_2_1029",@"--include",@"*.m",@"--include",@"*.xib"];
//    [self taskComand:@"grep" arguments:arrComand dir:nil];
    
    NSMutableArray  *arrUnusedFiles = [NSMutableArray array];
    NSMutableArray  *array = [NSMutableArray array];
    int count = 0;
    for (NSString  *strTemp in arraypngs)
    {
        count++;
        NSLog(@"\n----------------------------------%i  start-----------------------------\n",count);
        NSString  *strFile = [strTemp lastPathComponent];
        strFile = [strFile stringByReplacingOccurrencesOfString:@".pdf" withString:@""];
        if ([strFile rangeOfString:@"@2x."].location != NSNotFound ||
            [strFile rangeOfString:@"@3x."].location != NSNotFound)
        {
          
            NSArray  *arrComand = @[@"-r",@"-l",strFile,self.fileDir,@"--include",@"*.m",@"--include",@"*.xib"];
            
            NSArray  *arrInfo = [self taskComand:@"grep" arguments:arrComand dir:nil];
            if (arrInfo)
            {
                continue;
            }
         //   NSLog(@"strFile:%@ arrInfo:%@",strFile,arrInfo);
            
            NSString  *strFile2 = [strFile stringByReplacingOccurrencesOfString:@"@2x." withString:@"."];
            strFile2 = [strFile stringByReplacingOccurrencesOfString:@"@3x." withString:@"."];
            
            arrComand = @[@"-r",@"-l",strFile2,self.fileDir,@"--include",@"*.m",@"--include",@"*.xib"];
            
            NSArray  *arrInfo2 = [self taskComand:@"grep" arguments:arrComand dir:nil];
            if (arrInfo2)
            {
                
                continue;
            }
            
             NSLog(@"unused file:%@",strFile);
            
            if (![self arrayHasPrefixFileName:strFile2 inArray:arrUnusedFiles]) {
               [arrUnusedFiles addObject:strFile];
            }
        
            
            //NSLog(@"strFile2:%@ arrInfo:%@",strFile2,arrInfo2);
        }else
        {
            
            NSArray  *arrComand = @[@"-r",@"-l",strFile,self.fileDir,@"--include",@"*.m",@"--include",@"*.xib"];
            
            NSArray  *arrInfo = [self taskComand:@"grep" arguments:arrComand dir:nil];
            //NSLog(@"strFile:%@ arrInfo:%@",strFile,arrInfo);
            
            
            if (arrInfo)
            {
                continue;
            }
            NSString  *strFile2 = [strFile stringByReplacingOccurrencesOfString:@".png" withString:@"@2x.png"];
            
            arrComand = @[@"-r",@"-l",strFile2,self.fileDir,@"--include",@"*.m",@"--include",@"*.xib"];
            
            NSArray  *arrInfo2 = [self taskComand:@"grep" arguments:arrComand dir:nil];
            
            if (arrInfo2)
            {
                continue;
            }
            
            NSLog(@"unused file:%@",strFile);
            if (![self arrayHasPrefixFileName:strFile inArray:arrUnusedFiles]) {
                [arrUnusedFiles addObject:strFile ];
            }
            
            
           // NSLog(@"strFile2:%@ arrInfo:%@",strFile2,arrInfo2);
            
        }
        
        [array addObject:strTemp];
        
        NSLog(@"\n----------------------------------%i  end-----------------------------\n",count);
        
    }
    
    
    NSString  *docPath = [NSSearchPathForDirectoriesInDomains(NSDesktopDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString  *strFile = [docPath stringByAppendingPathComponent:@"resultofUnusedFiles.txt"];
    if (![[NSFileManager defaultManager] fileExistsAtPath:strFile])
    {
      //  NSError  *error = nil;
        BOOL  suc = [[NSFileManager defaultManager] createFileAtPath:strFile contents:nil attributes:nil];
        if (!suc)
        {
            NSLog(@"create file:%@ fail",strFile);
        }
        
    }
    
    NSString  *strInfo = [arrUnusedFiles componentsJoinedByString:@"\n"];
    [strInfo writeToFile:strFile atomically:NO encoding:NSUTF8StringEncoding error:nil];
    
    NSLog(@"unusedfiles:\n\n\n\n\n\n\n %@",arrUnusedFiles);
    
}




-(NSArray *)taskComand:(NSString*)comand arguments:(NSArray*)array  dir:(NSString *)strDoc
{
    NSTask *task = [[NSTask alloc] init];
    [task setLaunchPath:[NSString stringWithFormat:@"/usr/bin/%@",comand]];
    if (strDoc)
    {
        [task setCurrentDirectoryPath:strDoc];
    }
 
    
   // NSArray *arguments;
    // arguments = [NSArray arrayWithObjects: @"-l", @"-a", @"-t", nil];
    [task setArguments:array];
    
    NSPipe *pipe = [NSPipe pipe];
    [task setStandardOutput: pipe];
    
    NSFileHandle *file = [pipe fileHandleForReading];
 //   [task waitUntilExit];
    [task launch];
    
    
    
    
    NSMutableData *data = [[NSMutableData alloc] init];
    NSData *readData = nil;
    
    while ((readData = [file availableData])
           && [readData length]) {
        [data appendData: readData];
    }
    

    
    NSString *string = [[NSString alloc] initWithData: data
                                   encoding: NSUTF8StringEncoding];
    
    if (string == nil || [string isEqualToString:@""])
    {
        return nil;
    }
    NSArray  *resultarray = [string  componentsSeparatedByString:@"\n"];
    //[data release];
  //  NSLog(@"resultarray count:%ld",[resultarray count]);
  //  NSLog (@"got\n%@", resultarray);
    return resultarray;
}

-(void)receiveData:(NSNotification*)note
{
    
}

@end
